package com.kotlin.titlebar

import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager

class SystemStatusBarUtil {

    /**
     * 设置状态栏颜色
     * */
    fun statusBarTintColor(activity : AppCompatActivity, color : Int){
        //android5.0以上设置
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            activity.window.statusBarColor = color
        }

        //android4.4与5.0直接版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
            //透明状态栏
            activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            val androidContainer = activity.findViewById<ViewGroup>(android.R.id.content)
            //留出高度，设置setFitSystemWindows true代表会调整布局，会把状态栏高度留出来
            val contentView = androidContainer.getChildAt(0)
            if (contentView != null){
                contentView.fitsSystemWindows = true
            }
            //在原来的位置上添加一个状态栏
            val statusBarView = createStatusBarView(activity)
            androidContainer.addView(statusBarView, 0)
            statusBarView.setBackgroundColor(color)
        }
    }

    /**
     * 创建一个需要填充statusBarView
     */
    private fun createStatusBarView(activity: AppCompatActivity) : View{
        val statusBarView = View(activity)
        val statusBarParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity))

        statusBarView.layoutParams = statusBarParams

        return statusBarView
    }

    /**
     * 获取状态栏高度
     * */
    private fun getStatusBarHeight(activity: AppCompatActivity) : Int{
        var result = 0
        val resourceId = activity.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0){
            result = activity.resources.getDimensionPixelSize(resourceId)
        }

        return result
    }
}